import sys
import os
import time
#mycat ntp nfs  haproxy httpd  openstack-service mysql
# galera mariadb,rabbitmq,tomcat-cloud-web,tomcat-swift
class ServiceStarter():

    __Units = []
    workers = []
    monitor = None
    proxy = None
    connector = None


    def __init__(self):
        print sys.argv
        for i in range(1,len(sys.argv)):
            self.__Units.append(sys.argv[i])
        conf_pth = os.popen("find / -name Conf.cfg").readlines()[0].split("\n")[0]
    	reader = open(conf_pth)
        configs = reader.readlines()
        reader.close()
        for config in configs:
            temp = config.split(":")
            role = temp[0]
            ip = temp[1].strip()
            if role == "worker" and ip:
                self.workers.append(ip)
            elif role == "monitor" and ip:
            	self.monitor = ip
            elif role == "proxy" and ip:
                self.proxy = ip
            elif role == "connector" and ip:
            	self.connector = ip
            else:
            	pass

    def getProcessInfos(self,ip,keywords):
        processInfo = os.popen("ssh "+ip+" ps -ef|grep " +keywords+"|grep -v grep |awk '{print $2}'").readlines()
        return processInfo


    def checkMachinePower(self):
    	print("check worker nodes status...")
    	result = True
    	ips = []
    	for w in self.workers:
    	    ips.append(w)
    	ips.append(self.monitor)
    	if self.connector and self.connector != self.monitor:
    	    ips.append(self.connector)

    	for ip in ips:
	    print ip
    	    res = os.popen("ping -c 3 " +ip+ " | grep '0 received' | wc -l").readlines()[0].split("\n")[0]
    	    if res == "1":
    		result = False
    	return result

    def ceilometer(self):
    	print("[begin restart monitor service...]")
	os.system("ssh "+self.monitor +" \"/etc/init.d/mysql restart;mongod --shutdown --dbpath=/var/lib/mongodb/;mongod -f /etc/mongod.conf;openstack-service restart;\"")
    	if self.connector and self.monitor != self.connector:
    	    os.system("ssh "+self.connector +" \"/etc/init.d/mysql restart;mongod --shutdown --dbpath=/var/lib/mongodb/;mongod -f /etc/mongod.conf;openstack-service restart;\"")

    def tomcat_cloud_web(self):
    	print("[begin restart tomcat_cloud_web service...]")
        for workip in self.workers:
        	pnumber = None
	        processInfo = self.getProcessInfos(workip,"tomcat-cloud-web")
	        if len(processInfo):
	           pnumber = processInfo[0].split("\n")[0]
	        if pnumber != None:
	           os.system("ssh "+workip+" \"kill -9 "+pnumber+";export PATH=$PATH:/opt/jdk/bin;export JAVA_HOME=/opt/jdk;sh /opt/tomcat-cloud-web/bin/startup.sh\"")
	        else:
	           os.system("ssh "+workip+" \"export PATH=\$PATH:/opt/jdk/bin;export JAVA_HOME=/opt/jdk;/opt/tomcat-cloud-web/bin/startup.sh\"")
	
    def tomcat_oss(self):
    	print("[begin restart tomcat_oss service...]")
        for workip in self.workers:
            pnumber = None
	    processInfo = self.getProcessInfos(workip,"tomcat-swift")
	    if len(processInfo):
	       pnumber = processInfo[0].split("\n")[0]
	    if pnumber != None:
	       os.system("ssh "+workip+" \"kill -9 "+pnumber+";export PATH=$PATH:/opt/jdk/bin;export JAVA_HOME=/opt/jdk;sh /opt/tomcat-swift/bin/startup.sh\"")
	    else:
	       os.system("ssh "+workip+" \"export PATH=\$PATH:/opt/jdk/bin;export JAVA_HOME=/opt/jdk;/opt/tomcat-swift/bin/startup.sh\"")

    def rabbitmq(self):
    	print("[begin restart rabbitmq service...]")
        for workip in self.workers:
            pnumber = None
	    processInfo = self.getProcessInfos(workip,"rabbitmq_server")
	    if len(processInfo):
	       pnumber = processInfo[0].split("\n")[0]
	    if pnumber != None:
	       os.system("ssh "+workip+" \"kill -9 "+pnumber+";rabbitmq-server -detached;rabbitmqctl start_app;\"")
	    else:
	       os.system("ssh "+workip+" \"rabbitmq-server -detached;rabbitmqctl start_app;\"")

    def mysql(self):
    	print("[begin restart mysql service...]")
        for workip in self.workers:
            if self.workers.index(workip) == 0:
                os.system("ssh "+workip+" \"/etc/init.d/mysql stop;/etc/init.d/mysql bootstrap;\"")
                time.sleep(3)
	    else:
	       	os.system("ssh "+workip+" \"/etc/init.d/mysql restart;\"")

    def mycat(self):
        print("[begin restart mycat service...]")
        os.system("export PATH=$PATH:/usr/local/java/bin; /usr/local/mycat/bin/mycat restart")

    def apache(self):
        print("[begin restart apache service...]")
        os.system("systemctl restart httpd")
	
    def diskMount(self):
        print("[begin check storage dev mount...]")
        for workip in self.workers:
            mountNum = len(os.popen("ssh node2 df -TH |grep /storage").readlines())
            if mountNum == 0:
                os.system("ssh "+workip+" \"systemctl start rpcbind;mount -t nfs4 "+self.monitor+":/storage /storage;\"")

    def haproxy(self):
        print("[begin restart haproxy service...]")
        pnumber = None
        processInfo = self.getProcessInfos("localhost","haproxy")
        if len(processInfo):
	   pnumber = processInfo[0].split("\n")[0]
	if pnumber != None:
            os.system("kill -9 "+pnumber+";haproxy -f /etc/haproxy/haproxy.cfg")             
        else:
            os.system("haproxy -f /etc/haproxy/haproxy.cfg")

    def nfs(self):
    	print("[begin restart nfs service...]")
    	os.system("systemctl restart rpcbind.service;systemctl restart nfs-server.service")

    def ntp(self):
    	print("[begin restart ntp service...]")
    	os.system("systemctl restart ntpd.service")

    def startAll(self):
	while self.checkMachinePower() == False:
            time.sleep(1) 
	print "begin run................."
	self.mysql()
        self.diskMount()
    	self.rabbitmq()
    	self.nfs()
    	self.ntp()
    	self.apache()
    	self.haproxy()
    	self.mycat()
    	self.ceilometer()
    	self.tomcat_cloud_web()
        self.tomcat_oss()

    def main(self):
        if "tomcat" in self.__Units:
            self.tomcat_cloud_web()
            self.tomcat_oss()
        if "tomcat-cloud-web" in self.__Units:
            self.tomcat_cloud_web()
        if "tomcat-oss" in self.__Units:
            self.tomcat_oss()
        if "rabbitmq" in self.__Units:
            self.rabbitmq()
        if "mycat" in self.__Units:
            self.mycat()
        if "mysql" in self.__Units:
            self.mysql()
        if "nfs" in self.__Units:
            self.nfs()
        if "ntp" in self.__Units:
            self.ntp()
        if "apache" in self.__Units:
            self.apache()
        if "monitor" in self.__Units:
            self.ceilometer()
        if "all" in self.__Units:
#            str = raw_input("Are you sure restart all the IOP services?\n")
#	    if(str == "y" or str == "yes" or str == "Y" or str == "YES"):
	    self.startAll()
if __name__ == "__main__":
    S = ServiceStarter()
    S.main()
